package bilibli.utils;

import bilibli.pojo.Video;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DowloadUtil {

    private static  double downloaded = 0;
    private static double szie = 0;
    private static InputStream inputStream = null;
    //下载视频
    public synchronized static void dowload(Video video, String[] urls,String path) {
        System.out.println("数据大小:"+urls[1]+"字节");
        long start = System.currentTimeMillis();
        szie = Double.parseDouble(urls[1]);
        try {
            URL url = new URL(urls[0]);
            URLConnection urlConnection = url.openConnection();
            // 填需要爬取的av号
            urlConnection.setRequestProperty("Referer", "https://www.bilibili.com/video/" + video.getAid());
            urlConnection.setRequestProperty("Sec-Fetch-Mode", "no-cors");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
            urlConnection.setConnectTimeout(10 * 1000);
            inputStream = urlConnection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //定义路径
        String s = path + "\\/" + video.getTitle() + ".mp4";
        File file = new File(s);
        int i = 1;
        try {
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            byte[] bys = new byte[1024 * 1024];
            int len = 0;
            double downloaded = 0;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
                downloaded += len;
                Double v = (downloaded / Double.parseDouble(urls[1])) * 100;
                BigDecimal bg = new BigDecimal(v).setScale(2, RoundingMode.UP);
                System.out.println("已下载" + (bg) + "%");
                if (downloaded == szie) {
                    System.out.println("下载完毕");
                    System.out.println("花费的时间为"+((System.currentTimeMillis()-start)/1000)+"秒");

                }
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
